import org.acegisecurity.DisabledException
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;

class LoginController {

    AuthenticateService authenticateService

    def index = {
        if (isLoggedIn()) {
            redirect(uri: "/")
        } else {
            redirect(action: authorize, params: params)
        }
    }

    def authorize = {
        cacheToHeader(response)
        if (isLoggedIn()) {
            redirect(uri: "/")
        }
    }

    def ajaxAuthorize = {
        cacheToHeader(response)
        //this is example:
        render """
            <script type='text/javascript' language='JavaScript'>
                (function(){
                    //call function
                    loginForm();
                })();
            </script>
            """
    }

    def authorizationDenied = {
        redirect(uri: "/")
    }

    //deny page (data|view|json) for ajax access
    def ajaxAuthorizationDenied = {
        //this is example:
        render "{error:'access denied'}"
    }

    def authorizationFailed = {
        def username = ""
        if (session[AuthenticationProcessingFilter.ACEGI_SECURITY_LAST_USERNAME_KEY]!=null)
            username = session[AuthenticationProcessingFilter.ACEGI_SECURITY_LAST_USERNAME_KEY]
        def message = ""
        if (session[AuthenticationProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY]) {
            def exception = session[AuthenticationProcessingFilter.ACEGI_SECURITY_LAST_EXCEPTION_KEY]
            if (exception instanceof DisabledException) {
                message = g.message(code:'LoginController.authorizationFailed.disabled',args='$username')
            } else {
                message = g.message(code:'LoginController.authorizationFailed.failed')
            }
        }

        //is ajax access?
        def cnf = authenticateService.getAcegiConfig()
        def ajaxHeader = cnf.acegi.ajaxHeader
        def AJAX_HEADER = "${ajaxHeader}"
        boolean isAjax = false;
        if (session["ACEGI_SAVED_REQUEST_KEY"]) {
            def itr = session["ACEGI_SAVED_REQUEST_KEY"].getHeaderValues(AJAX_HEADER)
            if (itr.hasNext()) isAjax = true
        }

        if (isAjax) {
            render("{error:'${message}'}")
        } else {
            flash.message = message
            redirect(action:auth,params:params)
        }
    }

    def isLoggedIn() {
        def authPrincipal = authenticateService.principal()
        return (authPrincipal != null && authPrincipal != "anonymousUser")
    }

    def cacheToHeader(response) {
        response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
        response.addDateHeader("Expires", 0);
        response.setDateHeader("max-age", 0);
        response.setIntHeader("Expires", -1); //prevents caching at the proxy server
        response.addHeader("cache-Control", "private"); //IE5.x only;
    }
}